import React, { Component } from 'react'
import { Redirect } from 'react-router-dom';

class Login extends Component {

  constructor() {
    super();
    
    this.state = {
      redirectToReferer: false
    };
    // this.login = this.login.bind(this);
  }

  login = () => {
    fakeAuth.authenticate(() => {
      this.setState({ redirectToReferer: true });
    });
  }

  render () {
    const { from } = this.props.location.state || { from: { pathname: '/' }};
    const { redirectToReferer } = this.state;

    if (redirectToReferer) {
      return (
        <Redirect to={from} />
      );
    }

    return (
      <div>
        <p>You must log in to view the page at {from.pathname}</p>
        <button onClick={this.login}>Login in</button>
      </div>
    );
  }
}

export const fakeAuth = {
  isAuthenticated: false,
  authenticate(cb) {
    this.isAuthenticated = true;
    setTimeout(cb, 100);
  }
};

export default Login;
